<script setup lang="ts">
import { ref } from 'vue'
import type { Role, MenuList, MenuListResponseData } from '@/apis/acl/role/type'
import { getMenuListService, setPermissionService } from '@/apis/acl/role'
const dialogVisibel = ref<boolean>(false)

// roleId
const roleId = ref<string | number>('')
const open = (row: Role) => {
  dialogVisibel.value = true
  getMenuList(row.id as string)
  roleId.value = row.id as number
}

// / 默认勾选
const selectedMenu = ref<string[]>([])
// 获取菜单列表
const menuList = ref<MenuList>([])
const getMenuList = async (id: string) => {
  const res: MenuListResponseData = await getMenuListService(id)
  menuList.value = res.data
  selectedMenu.value = filterSelected(menuList.value, [])
}

defineExpose({
  open
})

const filterSelected = (menuList: MenuList, permissionId: string[]) => {
  menuList.forEach((item) => {
    if (item.select && item.level == '4') {
      permissionId.push(item.id as string)
    }
    if (item.children && item.children.length) {
      filterSelected(item.children, permissionId)
    }
  })

  return permissionId
}
// 确定
const treeRef = ref()

// 菜单栏勾选
const checked = ref()
const halfChecked = ref()
const permissionId = ref()
const onConfirm = async () => {
  checked.value = treeRef.value.getCheckedKeys()
  halfChecked.value = treeRef.value.getHalfCheckedKeys()

  permissionId.value = [...halfChecked.value, ...checked.value]

  await setPermissionService(roleId.value, permissionId.value)

  // 关闭弹窗
  dialogVisibel.value = false
  // 重新加载
  window.location.reload()
}
</script>

<template>
  <el-drawer title="分配权限" v-model="dialogVisibel">
    <template #default>
      <el-tree
        :data="menuList"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="selectedMenu"
        :props="{
          children: 'children',
          label: 'name'
        }"
        ref="treeRef"
      />
    </template>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisibel = false">取消</el-button>
        <el-button type="primary" @click="onConfirm">确定</el-button>
      </span>
    </template>
  </el-drawer>
</template>

<style scoped></style>
